import sys
import time
import decimal
sys.path.append("../modules/")
from BayesNetwork import BayesNetwork

BN = BayesNetwork()

class Experiment():
    def __init__(self):
        self.ini_structure = None
        self.target_structure = None
        self.class_variable = None
        self.exec_number = 0
        self.total_time = 0
        BN.showProgress = False
        BN.showTime = False
        BN.cores = 4
        
    def training(self, variables, data):
        BN.parse("$TARGET")
        
        # Target structure
        self.target_structure = BN.copy(BN.BayesianNetwork)
        #BN.generateBNStructureVisualization("./"+str(self.exec_number)+"/target", self.target_structure)
        
        # Creating initial structure
        initial_structure = BN.parse("$STRUCTURE")
        #initial_structure = BN.parse_encog("../../bug/log_ini_structure(old).eg")
        self.ini_structure = initial_structure
        
        BN.BayesianNetwork = None
        
        # DEFINE CLASS VARIABLE HERE
        class_variable = "$CLASSVAR"
        self.class_variable = class_variable
        
        # DEFINE EXPERIMENT
        # Simulated Annealing
        st = time.time()
        sys.stdout = open("./"+str(self.exec_number)+"/output.txt", "a")
        ESS_all, combinations = BN.computeAllESS(variables, data, self.ini_structure)
        bn_exp, res_score = BN.simulatedAnnealing(variables, data, ESS_all, self.ini_structure, BN.randomPerturbation, class_variable=self.class_variable, score_type="cll")
        self.total_time = time.time() - st
        print "Total time for experiment: " + str(self.total_time)
        sys.stdout = sys.__stdout__
        
        # Print result
        #BN.generateBNStructureVisualization("./"+str(self.exec_number)+"/alarm_final_structure_viz", bn_exp)
        BN.export_encog("./"+str(self.exec_number)+"/alarm_final_structure", bn_exp)
        
        return bn_exp

        
    def test(self,variables, data, structure):
        BN.BayesianNetwork = None
        #inverted, added, removed, likelihood_bn1, likelihood_bn2, bic_bn1, bic_bn2, cond_1, cond_2 = BN.compareBNStructures(self.ini_structure, structure, variables, data, class_variable=self.class_variable) 
        sys.stdout = open("./"+str(self.exec_number)+"/output.txt", "a")
        buffer = ""
        result= BN.compareBNStructures(self.ini_structure, structure, variables, data, class_variable=self.class_variable)
        buffer += str(result + tuple([str(self.total_time)])) + "\n"
        result= BN.compareBNStructures(self.target_structure, structure, variables, data, class_variable=self.class_variable)
        buffer += str(result + tuple([str(self.total_time)]))
        sys.stdout = sys.__stdout__
        
        out = open("./"+str(self.exec_number)+"/final_result", "a")
        out.write(buffer)
        out.close()
        self.exec_number += 1
        
        return buffer
    

